<template>
  <div class="user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="showAddUserDialog">
            添加用户
          </el-button>
        </div>
      </template>

      <!-- 用户列表 -->
      <el-table :data="userList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{row}">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === '启用' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{row}">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status">
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUserList, registerUser, updateUser, deleteUser } from '@/api/user';

const userList = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref('add');
const userForm = reactive({
  username: '',
  email: '',
  password: '',
  status: '启用'
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
};

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString();
};

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList();
    if (res.data.code === 200) {
      userList.value = res.data.data.list;
      total.value = res.data.data.total;
    } else {
      ElMessage.error(res.data.msg || '获取用户列表失败');
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查网络连接');
  }
};

// 显示添加用户对话框
const showAddUserDialog = () => {
  dialogType.value = 'add';
  Object.assign(userForm, {
    username: '',
    email: '',
    password: '',
    status: '启用'
  });
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = async (row) => {
  try {
    const res = await updateUser({
      name: row.name,
      password: 'new_password' // 这里需要实现密码修改逻辑
    });
    if (res.data.code === 200) {
      ElMessage.success('修改成功');
      fetchUserList();
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (error) {
    ElMessage.error('修改失败');
  }
};

// 删除用户
const handleDelete = async (row) => {
  try {
    const res = await deleteUser(row.id);
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      fetchUserList();
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 注册用户
const handleRegister = async (formData) => {
  try {
    const res = await registerUser(formData);
    if (res.data.code === 200) {
      ElMessage.success('注册成功');
      fetchUserList();
    } else {
      ElMessage.error(res.data.msg);
    }
  } catch (error) {
    ElMessage.error('注册失败');
  }
};

// 处理表单提交
const handleSubmit = async () => {
  try {
    const url = dialogType.value === 'add' 
      ? 'https://penglink.pcwxcn.top/api/admin/users'
      : `https://penglink.pcwxcn.top/api/admin/users/${userForm.id}`;
    
    const response = await fetch(url, {
      method: dialogType.value === 'add' ? 'POST' : 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      body: JSON.stringify(userForm)
    });

    const data = await response.json();
    if (data.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
      dialogVisible.value = false;
      fetchUserList();
    } else {
      ElMessage.error(data.msg || '操作失败');
    }
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchUserList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchUserList();
};

onMounted(() => {
  fetchUserList();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 